package com.cy.milktea.config.system;

import com.cy.milktea.pojo.System.Redis;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class RedisSessionDao extends AbstractSessionDAO {

    public static final long expireTime = 1000 * 60 * 30;  //--->设置过期时间

    @Autowired
    @Qualifier("redisTemplate2")  //---->解决shiro框架中的session序列化的问题
    private RedisTemplate redisTemplate2;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = this.generateSessionId(session);
        this.assignSessionId(session, sessionId);
        redisTemplate2.opsForValue().set(key(session.getId()), session, expireTime, TimeUnit.MILLISECONDS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return sessionId == null ? null : (Session) redisTemplate2.opsForValue().get(key(sessionId));
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session != null && session.getId() != null) {
            session.setTimeout(expireTime);
            redisTemplate2.opsForValue().set(key(session.getId()), session, expireTime, TimeUnit.MILLISECONDS);
        }
    }

    @Override
    public void delete(Session session) {
        if (session != null && session.getId() != null) {
            redisTemplate2.delete(key(session.getId()));
        }
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return redisTemplate2.keys(key("*"));
    }

    private String key(Object str) {
        return Redis.SHIRO_SESSION_PREFIX + str;
    }
}
